package com.association.main.frontcontroller;


import com.association.main.common.R;
import com.association.main.domain.*;
import com.association.main.dto.EventsDto;
import com.association.main.dto.NotificationsDto;
import com.association.main.service.*;
import com.association.main.utils.JwtUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
@Slf4j
@RestController
@RequestMapping("/front")
public class EventController {
    @Autowired
    private EventsService eventsService;


    @Autowired
    private UsersService usersService;

    @Autowired
    private ClubsService clubsService;

    @Autowired
    private JoinInfoService joinInfoService;



    @Autowired
    private SignupsService signupsService;

    @GetMapping("/events/list")
    public R<Page> eventsList(int page) {
        Page pageInfo = new Page(page, 10);
        LambdaQueryWrapper<Events> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq( Events::getTurnUser,"true");
        lambdaQueryWrapper.eq( Events::getStatus,1);
        lambdaQueryWrapper.select(Events::getId,
                Events::getName,
                Events::getCreatedAt,
                Events::getClubId,
                Events::getCreatedBy,
                Events::getLogo,
                Events::getNums
                );
        List<Events> list = eventsService.list(lambdaQueryWrapper);
        eventsService.page(pageInfo, lambdaQueryWrapper);
        List<EventsDto> eventsDtoList = list.stream().map((item) -> {
            Clubs clubs = clubsService.getById(item.getClubId());
            Users users = usersService.getById(item.getCreatedBy());
            LambdaQueryWrapper<Signups> signupsLambdaQueryWrapper=new LambdaQueryWrapper<>();
            signupsLambdaQueryWrapper.eq(Signups::getEventId,item.getId());
            int count = signupsService.count(signupsLambdaQueryWrapper);
            EventsDto eventsDto = new EventsDto(clubs.getName(), users.getName(), users.getEmail(), users.getPhone(),clubs.getLogo(),count);
            BeanUtils.copyProperties(item, eventsDto);
            return eventsDto;
        }).collect(Collectors.toList());
        pageInfo.setRecords(eventsDtoList);
        return R.success(pageInfo);
    }



    @GetMapping("/events/getById")
    public R<EventsDto> getEventById(int id) {
        LambdaQueryWrapper<Events> eventsLambdaQueryWrapper=new LambdaQueryWrapper<>();
        eventsLambdaQueryWrapper.eq(Events::getId,id);
        eventsLambdaQueryWrapper.eq( Events::getStatus,1);
        eventsLambdaQueryWrapper.select(Events::getId,
                Events::getName,
                Events::getCreatedAt,
                Events::getClubId,
                Events::getCreatedBy,
                Events::getLogo,
                Events::getStartTime,
                Events::getEndTime,
                Events::getDescription,
                Events::getNums
        );
        Events events = eventsService.getOne(eventsLambdaQueryWrapper);

        if (events == null) {
            return R.error("Event not found");
        }

        Clubs clubs = clubsService.getById(events.getClubId());
        Users users = usersService.getById(events.getCreatedBy());
        LambdaQueryWrapper<Signups> signupsLambdaQueryWrapper=new LambdaQueryWrapper<>();
        signupsLambdaQueryWrapper.eq(Signups::getEventId,events.getId());
        int count = signupsService.count(signupsLambdaQueryWrapper);
        EventsDto eventsDto = new EventsDto(clubs.getName(), users.getName(), users.getEmail(), users.getPhone(),clubs.getLogo(),count);
        BeanUtils.copyProperties(events, eventsDto);
        return R.success(eventsDto);
    }

    @GetMapping("/events/mylist")
    public R<Page> myEventsList(int page, HttpServletRequest request) {
        String token = request.getHeader("token");
        Integer userId = JwtUtil.getUserId(token);
        LambdaQueryWrapper<JoinInfo> joinInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        joinInfoLambdaQueryWrapper.eq(JoinInfo::getMemberId, userId);
        List<JoinInfo> joinInfoList = joinInfoService.list(joinInfoLambdaQueryWrapper);
        Page<EventsDto> pageInfo = new Page<>(page, 10);
        if(joinInfoList.size()>0){
            List<Integer> joinClubIds = joinInfoList.stream().map(JoinInfo::getClubId).collect(Collectors.toList());
            LambdaQueryWrapper<Events> eventsLambdaQueryWrapper = new LambdaQueryWrapper<>();
            eventsLambdaQueryWrapper.in(Events::getClubId, joinClubIds);
            eventsLambdaQueryWrapper.select(Events::getId,
                    Events::getName,
                    Events::getCreatedAt,
                    Events::getClubId,
                    Events::getCreatedBy,
                    Events::getLogo,
                    Events::getStartTime,
                    Events::getEndTime,
                    Events::getNums
            );
            List<Events> eventsList = eventsService.list(eventsLambdaQueryWrapper);
            List<EventsDto> eventsDtoList = eventsList.stream().map(events -> {
                Clubs clubs = clubsService.getById(events.getClubId());
                Users users=usersService.getById(events.getCreatedBy());
                LambdaQueryWrapper<Signups> signupsLambdaQueryWrapper=new LambdaQueryWrapper<>();
                signupsLambdaQueryWrapper.eq(Signups::getEventId,events.getId());
                int count = signupsService.count(signupsLambdaQueryWrapper);
                EventsDto eventsDto = new EventsDto(clubs.getName(), users.getName(), users.getEmail(), users.getPhone(),clubs.getLogo(),count);
                BeanUtils.copyProperties(events, eventsDto);
                return eventsDto;
            }).collect(Collectors.toList());

            pageInfo.setRecords(eventsDtoList);
        }

        return R.success(pageInfo);
    }

    @PostMapping("/events/takepart")
    public R<String> takePartEvent(int id, HttpServletRequest request) {
        String token = request.getHeader("token");
        Integer userId = JwtUtil.getUserId(token);

        // 获取用户ID
        LambdaQueryWrapper<Signups> signupsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        signupsLambdaQueryWrapper.eq(Signups::getEventId, id);
        signupsLambdaQueryWrapper.eq(Signups::getMemberId, userId);
        Signups signups = signupsService.getOne(signupsLambdaQueryWrapper);
        int count = signupsService.count(signupsLambdaQueryWrapper);
        // 获取活动信息
        Events event = eventsService.getById(id);


        if (count>=event.getNums()){
            return R.error("参与失败，活动人数已经满了");
        }
        // 判断活动是否在开始时间和结束时间之间
        LocalDateTime now = LocalDateTime.now();
        if (!event.getStartTime().isAfter(now)) {
            return R.error("活动已经开始或结束");
        }

        // 先判断此用户有没有参与过此活动
        if (signups == null) {
            // 没有参与
            Signups signups1 = new Signups();
            signups1.setEventId(id);
            signups1.setCreatedAt(LocalDateTime.now());
            signups1.setMemberId(userId);
            boolean save = signupsService.save(signups1);
            if (save) {
                return R.success("参与成功！");
            } else {
                return R.error("参与失败可能是活动已经被取消");
            }
        }
        return R.error("你已经参与了本活动了");
    }

    @GetMapping("/events/mypart")
    public R<Page> myEventsPart(int page, HttpServletRequest request) {
        String token = request.getHeader("token");
        Integer userId = JwtUtil.getUserId(token);
        Page<EventsDto> pageInfo = new Page<>(page, 10);
        LambdaQueryWrapper<Signups> signupsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        signupsLambdaQueryWrapper.eq(Signups::getMemberId, userId);

        List<Signups> signupsList = signupsService.list(signupsLambdaQueryWrapper);
        if(signupsList.size()>0){
            List<Integer> eventIds = signupsList.stream().map(Signups::getEventId).collect(Collectors.toList());

            LambdaQueryWrapper<Events> eventsLambdaQueryWrapper = new LambdaQueryWrapper<>();
            eventsLambdaQueryWrapper.in(Events::getId, eventIds);
            eventsLambdaQueryWrapper.select(Events::getId,
                    Events::getName,
                    Events::getCreatedAt,
                    Events::getClubId,
                    Events::getCreatedBy,
                    Events::getLogo,
                    Events::getStartTime,
                    Events::getEndTime,
                    Events::getDescription,
                    Events::getNums
            );
            List<Events> eventsList = eventsService.list(eventsLambdaQueryWrapper);

            List<EventsDto> eventsDtoList = eventsList.stream().map(events -> {
                Clubs clubs = clubsService.getById(events.getClubId());
                Users users = usersService.getById(events.getCreatedBy());
                LambdaQueryWrapper<Signups> signupsLambdaQueryWrapper1=new LambdaQueryWrapper<>();
                signupsLambdaQueryWrapper1.eq(Signups::getEventId,events.getId());
                int count = signupsService.count(signupsLambdaQueryWrapper1);
                EventsDto eventsDto = new EventsDto(clubs.getName(), users.getName(), users.getEmail(), users.getPhone(),clubs.getLogo(),count);
                BeanUtils.copyProperties(events, eventsDto);
                return eventsDto;
            }).collect(Collectors.toList());


            pageInfo.setRecords(eventsDtoList);

            return R.success(pageInfo);
        }
        return R.success(pageInfo);

    }

    @GetMapping("/events/isEvent")
    public R<String> isEvent(Integer eventId,HttpServletRequest request){
        String token = request.getHeader("token");
        Integer userId = JwtUtil.getUserId(token);
        LambdaQueryWrapper<Signups> signupsLambdaQueryWrapper=new LambdaQueryWrapper<>();
        signupsLambdaQueryWrapper.eq(Signups::getEventId,eventId);
        signupsLambdaQueryWrapper.eq(Signups::getMemberId,userId);
        int count = signupsService.count(signupsLambdaQueryWrapper);
        if(count<=0){
            return R.success("no");
            //说明没有参加
        }else{
            return R.success("yes");
        }
    }


    @PostMapping("/events/quit")
    public R<String> quitEvent(int id, HttpServletRequest request){
        String token = request.getHeader("token");
        Integer userId = JwtUtil.getUserId(token);

        // 查询报名记录
        LambdaQueryWrapper<Signups> signupsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        signupsLambdaQueryWrapper.eq(Signups::getEventId, id);
        signupsLambdaQueryWrapper.eq(Signups::getMemberId, userId);
        Signups signups = signupsService.getOne(signupsLambdaQueryWrapper);

        // 判断活动是否开始
        Events event = eventsService.getById(id);
        LocalDateTime now = LocalDateTime.now();
        if (now.isAfter(event.getStartTime())) {
            return R.error("活动已开始，无法退出");
        }

        // 如果报名记录存在，删除报名记录
        if(signups != null){
            boolean remove = signupsService.removeById(signups.getId());
            if(remove){
                return R.success("退出成功");
            }else{
                return R.error("退出失败");
            }
        }else{
            return R.error("未参加此活动");
        }
    }



}